﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using PMS.BusinessFacade;
using PMS.EntityManage;
using PMS.Common;
using PMS.EntityQuery;
using System.Data.SqlClient;
using System.Collections.Generic;

public partial class Modules_Personal_TargetList : System.Web.UI.Page
{
    IPerf_Personal_TargetOwnerHandler toHandler = new Perf_Personal_TargetOwnerManage();
    IPerf_Personal_TargetHandler targetHandler = new Perf_Personal_TargetManage();
    IPerf_Personal_TargetTypeHandler ttHandler = new Perf_Personal_TargetTypeManage();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!CheckPurviews())
        {
            Response.Redirect("~/Login.aspx");
        }
        if (!IsPostBack)
        {
            ViewState["OrderBy"] = "Id";
            ViewState["Accending"] = "asc";

            SqlParameter[] parms = null;
            string clause = " 1=1 ";
            ProcessOwnerParms(ref clause, ref parms);
            ownerDataBind(clause, parms);
        }
    }

    private bool CheckPurviews()
    {
        if (Session["UserPurviews"] != null)
        {
            string strPur = Session["UserPurviews"].ToString();
            if (strPur.Contains("301030"))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }

    #region 指标套
    
    
    /// <summary>
    /// 初始化指标套信息表
    /// </summary>
    private void ownerDataBind(string whereClause, SqlParameter[] parms)
    {
        try
        {
            SqlParameter[] parms2 = null;
            int counter = 0;
            DataTable dt = new DataTable();

            if (whereClause != string.Empty)
            {
                dt = toHandler.GetPerf_Personal_TargetOwnerByPageList(whereClause, parms, ViewState["OrderBy"].ToString() + " " + ViewState["Accending"].ToString(), AspNetPager.StartRecordIndex - 1, AspNetPager.PageSize);
                whereClause = "1=1";
                ProcessOwnerParms(ref whereClause, ref parms2);
                counter = toHandler.GetCounter(whereClause, parms2);
            }
            else
            {
                dt = toHandler.GetPerf_Personal_TargetOwnerByPageList(ViewState["OrderBy"].ToString() + " " + ViewState["Accending"].ToString(), AspNetPager.StartRecordIndex - 1, AspNetPager.PageSize);
                counter = toHandler.GetCounter();
            }

            this.AspNetPager.RecordCount = counter;
            gvTargetOwnerList.DataSource = dt;
            gvTargetOwnerList.DataBind();

            ChangeUIVisibility(false);

            FillTargetType();
        }
        catch
        {
            Jscript.AlertInAjax("連接錯誤!", UpdatePanel1);
            return;
        }
    }

    /// <summary>
    /// 条件参数处理
    /// </summary>
    /// <param name="whereClause"></param>
    /// <param name="parms"></param>
    private void ProcessOwnerParms(ref string whereClause, ref SqlParameter[] parms)
    {
        List<SqlParameter> lstParm = new List<SqlParameter>();

        if (txtName.Text != string.Empty)
        {
            whereClause += " and Name like + '%' + @Name + '%'";
            lstParm.Add(new SqlParameter("@Name", txtName.Text.Trim()));
        }

        parms = lstParm.ToArray();
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        SqlParameter[] parms = null;
        string clause = " 1=1 ";
        ProcessOwnerParms(ref clause, ref parms);
        ownerDataBind(clause, parms);
    }

    protected void gvTargetOwnerList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        //
        if (e.CommandName == "view")
        {
            int id = Convert.ToInt32(e.CommandArgument.ToString().Trim());
            try
            {
                string clause = " 1=1 ";
                SqlParameter[] parms = null;
                ProcessTargetParms(ref clause, ref parms, id);
                targetDataBind(clause, parms, id);
                ChangeUIVisibility(true);
            }
            catch
            {
                Jscript.AlertInAjax("操作失败!", UpdatePanel1);
            }
        }
    }

    protected void gvTargetOwnerList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            
            if (e.Row.RowIndex > -1)
            {
                e.Row.Cells[2].Text = Enums.GetPersonalTargetOwnerStatus((Enums.PersonalTargetOwnerStatus)int.Parse(e.Row.Cells[2].Text));
            }
        }
    }

    protected void gvTargetOwnerList_Sorting(object sender, GridViewSortEventArgs e)
    {

        if (e.SortExpression.ToLower() == ViewState["OrderBy"].ToString().ToLower())
        {
            if (ViewState["Accending"].ToString().ToLower() == "asc")
            {
                ViewState["Accending"] = "desc";
            }
            else
            {
                ViewState["Accending"] = "asc";
            }
        }
        else
        {
            ViewState["OrderBy"] = e.SortExpression;
        }

        SqlParameter[] parms = null;
        string clause = " 1=1 ";
        ProcessOwnerParms(ref clause, ref parms);
        ownerDataBind(clause, parms);
    }
    
    protected void AspNetPager_PageChanged(object src, EventArgs e)
    {
        SqlParameter[] parms = null;
        string clause = " 1=1 ";
        ProcessOwnerParms(ref clause, ref parms);
        ownerDataBind(clause, parms);
    }
    #endregion

    private void ChangeUIVisibility(bool isTargetView)
    {
        divTargetTitle.Style.Add("display", isTargetView ? "block" : "none");
        searchContainer.Style.Add("display", isTargetView ? "none" : "block");
        divTargetSearch.Style.Add("display", isTargetView ? "block" : "none");
        gvTargetList.Visible = isTargetView;
        gvTargetOwnerList.Visible = !isTargetView;
        AspNetPager.Visible = !isTargetView;
        AspNetPager1.Visible = isTargetView;
    }


    ////////////////////////////////////// 指标 /////////////////////////////////////////////
    #region 指标

    private void FillTargetType()
    {
        DataTable dt = ttHandler.GetPerf_Personal_TargetTypeList(" Status = @Status", new SqlParameter[] { new SqlParameter("@Status", (int)Enums.NormalStatus.Vallid) }, " id asc");
        ddlTargetType.DataTextField = "Name";
        ddlTargetType.DataValueField = "ID";
        ddlTargetType.DataSource = dt;
        ddlTargetType.DataBind();
        ddlTargetType.Items.Add(new ListItem("全部...", "0"));
        ddlTargetType.SelectedValue = "0";
    }

    /// <summary>
    /// 初始化指标信息表
    /// </summary>
    private void targetDataBind(string whereClause, SqlParameter[] parms, int ownerId)
    {
        try
        {
            Perf_Personal_TargetOwnerQuery query = toHandler.GetPerf_Personal_TargetOwnerQuery(ownerId);
            lblTargetOwnerName.Text = query.Name;
            hdnSelectedTargetOwnerID.Value = ownerId.ToString();

            if (query.Status != (int)Enums.PersonalTargetOwnerStatus.NewAdded)
            {
                btnCreate.Visible = false;
                ViewState["CanEdit"] = false;
            }
            else
            {
                btnCreate.Visible = true;
                ViewState["CanEdit"] = true;
            }


            SqlParameter[] parms2 = null;
            int counter = 0;
            DataTable dt = new DataTable();

            if (whereClause != string.Empty)
            {
                dt = targetHandler.GetPerf_Personal_TargetByPageList(whereClause, parms, ViewState["OrderBy"].ToString() + " " + ViewState["Accending"].ToString(), AspNetPager1.StartRecordIndex - 1, AspNetPager1.PageSize);
                whereClause = "1=1";
                ProcessTargetParms(ref whereClause, ref parms2, ownerId);
                counter = targetHandler.GetCounter(whereClause, parms2);
            }
            else
            {
                dt = targetHandler.GetPerf_Personal_TargetByPageList(ViewState["OrderBy"].ToString() + " " + ViewState["Accending"].ToString(), AspNetPager1.StartRecordIndex - 1, AspNetPager1.PageSize);
                counter = targetHandler.GetCounter();
            }

            this.AspNetPager1.RecordCount = counter;
            gvTargetList.DataSource = dt;
            gvTargetList.DataBind();

            ChangeUIVisibility(true);
        }
        catch
        {
            Jscript.AlertInAjax("連接錯誤!", UpdatePanel1);
            return;
        }
    }

    /// <summary>
    /// 条件参数处理
    /// </summary>
    /// <param name="whereClause"></param>
    /// <param name="parms"></param>
    private void ProcessTargetParms(ref string whereClause, ref SqlParameter[] parms, int ownerId)
    {
        List<SqlParameter> lstParm = new List<SqlParameter>();

        whereClause += " and TargetOwner_ID = @TargetOwner_ID";
        lstParm.Add(new SqlParameter("@TargetOwner_ID", ownerId));

        if (ViewState["TargetCode"] != null)
        {
            whereClause += " and Code like '%' + @Code + '%'";
            lstParm.Add(new SqlParameter("@Code", ViewState["TargetCode"].ToString()));
        }
        if (ViewState["TargetType"] != null)
        {
            whereClause += " and TargetType_ID = @TargetType_ID ";
            lstParm.Add(new SqlParameter("@TargetType_ID", int.Parse(ViewState["TargetType"].ToString())));
        }

        parms = lstParm.ToArray();
    }
    
    
    protected void gvTargetList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "del")
        {
            try
            {
                int id = Convert.ToInt32(e.CommandArgument.ToString().Trim());
                // 判断是否能够删除

                targetHandler.DeletePerf_Personal_Target(id);
                Jscript.AlertInAjax("操作成功!", UpdatePanel1);
                RefreshTargetList();
            }
            catch
            {
                Jscript.AlertInAjax("操作失败!", UpdatePanel1);
            }
        }
        else if (e.CommandName == "edt")
        {
            RefreshTargetList();
        }
    }

    protected void gvTargetList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (ViewState["CanEdit"] != null)
            {
                bool canEdit = (bool)ViewState["CanEdit"];
                if (!canEdit)
                {
                    ImageButton ibtnEdit = (ImageButton)e.Row.FindControl("ibtnEdit");
                    ImageButton ibtnDel = (ImageButton)e.Row.FindControl("ibtnDelete");
                    ibtnEdit.Visible = false;
                    ibtnDel.Visible = false;
                }
            }

            if (e.Row.RowIndex > -1)
            {
                e.Row.Cells[6].Text = Enums.GetNormalStatusName((Enums.NormalStatus)int.Parse(e.Row.Cells[6].Text));
                e.Row.Cells[5].Text = Enums.GetYesNoStatus((Enums.YesNoStatus)int.Parse(e.Row.Cells[5].Text));

                int targetTypeId = int.Parse(e.Row.Cells[3].Text);
                Perf_Personal_TargetTypeQuery query = ttHandler.GetPerf_Personal_TargetTypeQuery(targetTypeId);
                if (query != null)
                    e.Row.Cells[3].Text = query.Name;
            }
        }
    }

    protected void gvTargetList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderBy"].ToString().ToLower())
        {
            if (ViewState["Accending"].ToString().ToLower() == "asc")
            {
                ViewState["Accending"] = "desc";
            }
            else
            {
                ViewState["Accending"] = "asc";
            }
        }
        else
        {
            ViewState["OrderBy"] = e.SortExpression;
        }

        RefreshTargetList();
    }

    protected void LBtnBack_Click(object sender, EventArgs e)
    {
        ChangeUIVisibility(false);

        SqlParameter[] parms = null;
        string clause = " 1=1 ";
        ProcessOwnerParms(ref clause, ref parms);
        ownerDataBind(clause, parms);
    }

    protected void CreateTarget_Click(object sender, EventArgs e)
    {
        RefreshTargetList();
    }

    protected void AspNetPager1_PageChanged(object src, EventArgs e)
    {
        RefreshTargetList();
    }

    protected void btnSearchTarget_Click(object sender, EventArgs e)
    {
        if (txtTargetCode.Text != string.Empty && !"".Equals(txtTargetCode.Text.Trim()))
            ViewState["TargetCode"] = txtTargetCode.Text.Trim();
        else
            ViewState["TargetCode"] = null;

        if (ddlTargetType.SelectedValue != string.Empty && !"".Equals(ddlTargetType.SelectedValue) && !"0".Equals(ddlTargetType.SelectedValue))
            ViewState["TargetType"] = ddlTargetType.SelectedValue;
        else
            ViewState["TargetType"] = null;

        RefreshTargetList();
    }

    private void RefreshTargetList()
    {
        int ownerId = int.Parse(hdnSelectedTargetOwnerID.Value);
        string caluse = " 1=1 ";
        SqlParameter[] parms = null;
        ProcessTargetParms(ref caluse, ref parms, ownerId);
        targetDataBind(caluse, parms, ownerId);
    }


    #endregion
}
